﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lk.WebTow.Authorize;
using Lk.WebTow.Common.Cache;
using Lk.WebTow.Data;
using Lk.WebTow.Models;
using Microsoft.AspNetCore.Mvc;

namespace Lk.WebTow.Areas.Admin.Controllers
{
    public class HomeController : BaseController
    {
        public HomeController(ApplicationDbContext dbContext) : base(dbContext)
        {
        }

        [SkipAdminAuthorizeAttribute]
        public IActionResult Index()
        {
            return View();
        }

        public ActionResult Center()
        {
            string strIp = "-";
            string strBackIp = "-";
            string strBackIime = "-";
            if (siteAdminInfo != null)
            {
            }
            ViewData["strIp"] = strIp;
            ViewData["strBackIp"] = strBackIp;
            ViewData["strBackIime"] = strBackIime;
            ViewBag.SetConf = siteConfig;
            return View();
        }

        public JsonResult GetSysMenu()
        {

            if (!IsAdminLogin())
            {
                return Json(new { status = 1, message = "管理员信息异常" });
            }
            var roleModel = dbContext.NcManagerRole.FirstOrDefault(s => s.Id == siteAdminInfo.RoleId);
            if (roleModel == null)
            {
                return Json(new { status = 1, message = "获取角色异常" });
            }
            List<NcManagerRoleValue> roleValues = null;
            if (siteAdminInfo.RoleType > 1)//排除超级管理员
            {
                roleValues = dbContext.NcManagerRoleValue.Where(s => s.RoleId == siteAdminInfo.RoleId).ToList();
                if (roleValues == null)
                {
                    return Json(new { status = 1, message = "获取角色异常" });
                }
            }

            var navList = this.GetNavCacheList().Where(s => s.NavType == "System").ToList();

            StringBuilder strJson = new StringBuilder();
            var msg = GetNavTree(strJson, navList, 0, (int)roleModel.RoleType, roleValues);

            return Json(new { status = 0, message = msg });
        }
        private string GetNavTree(StringBuilder strJson, List<NcNavigation> oldNavigation, int parentId, int roleType, List<NcManagerRoleValue> ls)
        {
            var list = oldNavigation.Where(s => s.ParentId == parentId).ToList();
            bool isWrite = false;

            for (var i = 0; i < list.Count(); i++)
            {
                //检查是否显示在界面上
                bool isActionPass = true;
                if (list[i].IsLock == 1)
                {
                    isActionPass = false;
                }
                //检查管理员权限
                if (isActionPass && roleType > 1)
                {
                    string[] actionTypeArr = list[i].ActionType.Split(',');
                    foreach (var item in actionTypeArr)
                    {
                        if (item == "Show")
                        {
                            NcManagerRoleValue modelt = ls.Find(p => p.NavName == list[i].Name && p.ActionType == "Show");
                            if (modelt == null)
                            {
                                isActionPass = false;
                            }
                        }
                    }
                }
                if (!isActionPass)
                {
                    if (i == (list.Count() - 1) && parentId != 0)
                    {
                        strJson.Append("</ul>\n");
                    }
                    continue;//循环下一条
                }
                //如果没有该权限则不显示

                #region--拼接开始--
                string strIClass = string.Empty;
                //如果是顶级导航
                if (parentId == 0)
                {
                    strJson.Append("<div class=\"side-menu-group active\">\n");
                    string iconStyle = "fa-gears";
                    if (!string.IsNullOrEmpty(list[i].IconUrl.ToString().Trim()))
                    {
                        iconStyle = list[i].IconUrl.ToString().Trim('.');//只用css
                    }
                    strJson.Append("<h1 title=\"" + list[i].SubTitle + "\" main-nav-icon=\"fa " + iconStyle + "\">");

                    strJson.Append("<i class=\"fa " + iconStyle + "\"></i></h1>\n");
                    strJson.Append("<div class=\"side-menu-wrap\">\n");
                    strJson.Append("<h2><i class=\"fa " + iconStyle + "\"></i><span>" + list[i].Title + "</span><b class=\"fa fa-angle-double-down\"></b></h2>\n");
                    //调用自身迭代
                    this.GetNavTree(strJson, oldNavigation, int.Parse(list[i].Id.ToString()), roleType, ls);
                    strJson.Append("    </div>\n");
                    strJson.Append("</div>\n");
                }
                else//下级导航
                {
                    if (!isWrite)
                    {
                        isWrite = true;
                        strJson.Append("<ul class=\"nav\">\n");
                    }
                    strJson.Append("<li>\n");
                    strJson.Append("<a");
                    if (!string.IsNullOrEmpty(list[i].LinkUrl))
                    {
                        if (list[i].ChannelId.Value > 0)
                        {
                            strJson.Append(" class=\"J_menuItem\" href=\"" + list[i].LinkUrl + "?channel_id=" + list[i].ChannelId + "\"");
                        }
                        else
                        {
                            strJson.Append(" class=\"J_menuItem\" href=\"" + list[i].LinkUrl + "\"");
                        }
                    }
                    strJson.Append(">");
                    string iconStyle = "fa-bars";
                    if (!string.IsNullOrEmpty(list[i].IconUrl.Trim()))
                    {
                        iconStyle = list[i].IconUrl.TrimStart('.');
                    }
                    strJson.Append("<i class=\"fa " + iconStyle + "\"></i>" + list[i].Title + "</a>\n");
                    //调用自身迭代
                    this.GetNavTree(strJson, oldNavigation, list[i].Id, roleType, ls);
                    strJson.Append("</li>\n");

                    if (i == (list.Count() - 1))
                    {
                        strJson.Append("</ul>\n");
                    }
                }
                #endregion
            }
            return strJson.ToString();

        }

        #region db


        public List<MenuViewModel> GetNavList()
        {
            var list = GetNavCacheList();
            if (list == null)
            {
                return null;
            }
            List<MenuViewModel> newMenuViews = new List<MenuViewModel>();
            GetNavList(newMenuViews, list, 0, 0);
            return newMenuViews;
        }

        private void GetNavList(List<MenuViewModel> newMenuViews, List<NcNavigation> list, int parentId, int classLayer)
        {
            classLayer++;
            List<MenuViewModel> menuViews = new List<MenuViewModel>();
            var parentList = list.Where(s => s.ParentId == parentId).ToList();
            for (int i = 0; i < list.Count(); i++)
            {
                var model = new MenuViewModel();
                for (int j = 0; j < parentList.Where(s => s == list[i]).Count(); j++)
                {
                    model = (new MenuViewModel() { Name = parentList[j].Name });
                }
                model.ClassLayer = classLayer;
                newMenuViews.AddRange(menuViews);

                GetNavList(newMenuViews, list, parentList[i].Id, classLayer);
            }
        }
        private List<NcNavigation> GetNavCacheList()
        {
            var resultCaches = RedisHelper.Default.GetStringKey<List<NcNavigation>>("GetNavCacheList");
            //var resultCaches = CacheHelper.Get<List<NcNavigation>>("GetNavCacheList");
            if (resultCaches != null && resultCaches.Count > 0)
            {
                return resultCaches;
            }
            var result = dbContext.NcNavigation.OrderBy(s => s.SortId).ThenBy(s => s.Id).ToList();
            RedisHelper.Default.SetStringKey<List<NcNavigation>>("GetNavCacheList", result, TimeSpan.FromDays(1));//一天
            return result;
        }
        #endregion
    }
}